#!/bin/bash

# This script will be invoked by lastore-update-metadata-info.timer every 3 hours
# 1. Trigger a apt-get update, so other component can update /var/lib/lastore/update_infos.json.
# 2. Pull appstore.deepin.com's metadata by lastore-tools,
#    inlcude a large ostree repo and some small json metadata.

function systemd_update_metadata_info()
{
    systemctl start lastore-update-metadata-info.service
}

function update_metadata_info_now()
{
    #remote=$(cat /var/lib/lastore/scripts/metadata_remote)
    #fix_remote_url $remote
    #/usr/bin/lastore-tools metadata -u --remote=$remote
    /usr/bin/lastore-tools update -r desktop -j applications -o /var/lib/lastore/applications.json
    #/usr/bin/lastore-tools update -r desktop -j categories -o /var/lib/lastore/categories.json
    #/usr/bin/lastore-tools update -r desktop -j xcategories -o /var/lib/lastore/xcategories.json
    #/usr/bin/lastore-tools update -r desktop -j mirrors -o /var/lib/lastore/mirrors.json
}

function fix_remote_url()
{
    repo_dir=/var/lib/lastore/tree
    config_url=$1
    if [ -f $repo_dir/config -a -n "$config_url" ]; then
        # repo config file exist and $config_url is not empty
        if which ostree >/dev/null; then
            # has ostree
            current_url=$(ostree --repo=$repo_dir config get 'remote "origin".url')
            if [ "$current_url" != "$config_url" ]; then
                echo remove $repo_dir
                rm -rf $repo_dir
            fi
        fi
    fi
}


which ostree >/dev/null || exit 0

case "$1" in
    "-now")
        update_metadata_info_now
        exit 0
        ;;
    *)
        if [[ -S /var/run/systemd/notify ]]; then
            systemd_update_metadata_info
        else
            update_metadata_info_now
        fi
        ;;
esac



